package com.github.pig.stock.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.common.util.UserUtils;
import com.github.pig.common.vo.UserVo;
import com.github.pig.stock.common.enums.OrderStatus;
import com.github.pig.stock.entity.TblStock;
import com.github.pig.stock.mapper.TblStockMapper;
import com.github.pig.stock.model.dto.StockInDTO;
import com.github.pig.stock.model.dto.StockSearchDTO;
import com.github.pig.stock.service.ITblStockService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pig.stock.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author J神
 * @since 2018-05-07
 */
@Service
@Slf4j
public class TblStockServiceImpl extends ServiceImpl<TblStockMapper, TblStock> implements ITblStockService {
    private String           val = null;
    private SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
    private DecimalFormat df = new DecimalFormat("0");
    @Autowired
    private UserService userService;
    @Autowired
    private TblStockMapper tblStockMapper;
    /**
     * @return
     */
    @Override
    public JSONObject readStockInExecl(InputStream inputStream) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
        HSSFSheet sheet = null;
        sheet = workbook.getSheetAt(0);
        JSONObject result=new JSONObject();
        List<Integer> rightList=new ArrayList<>();
        List<Integer> errorList=new ArrayList<>();
        for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
                HSSFRow row = sheet.getRow(j);
                if (row != null&& row.getCell(0)!=null) {
                    TblStock tblStock=new TblStock();
                    try{
                        //日期
                        Date d= main((int)row.getCell(0).getNumericCellValue());
                        //订单号
                        String orderNo=getXCellVal(row.getCell(1));
                        //订单信息
                        String orderInfo=getXCellVal(row.getCell(2));
                        //订单商品数量
                        String orderNum=getXCellVal(row.getCell(3));
                        //地址
                        String orderMoney=getXCellVal(row.getCell(4));
                        //收货人
                        String orderUserName=getXCellVal(row.getCell(6));
                        //收货地址
                        String orderUserAddress=getXCellVal(row.getCell(8));
                        tblStock.setOrderNum(Integer.valueOf(orderNum));
                        tblStock.setOrderMoney(new BigDecimal(orderMoney));
                        tblStock.setOrderUserName(orderUserName);
                        tblStock.setOrderId(orderNo);
                        tblStock.setOrderInfo(orderInfo);
                        tblStock.setGmtOrder(d);
                        tblStock.setOrderAddress(orderUserAddress);
                        tblStock.setCreateBy(UserUtils.getUser());
                        tblStock.setGmtCreate(new Date());
                        tblStock.setOrderStatus(OrderStatus.WAIT_DISTRIBUTE);
                        this.insert(tblStock);
                        rightList.add(j+1);
                    }
                    catch (Exception e){
                        log.error("订单入库异常:{},出错行数:{}",e,j+1);
                        errorList.add(j+1);
                    }

                }
                else {
                    break;
                }
            }
        result.put("right",rightList);
        result.put("error",errorList);
        return result;
    }

    @Override
    public Page<TblStock> search(StockSearchDTO stockSearchDTO) {
        Page page=new Page();
        page.setSize(stockSearchDTO.getLimit());
        page.setCurrent(stockSearchDTO.getPage());
        if(stockSearchDTO.getIds()!=null&&stockSearchDTO.getIds().size()>0){
            page.setSize(stockSearchDTO.getIds().size());
        }
        return page.setRecords(tblStockMapper.selectListByCondition(stockSearchDTO,page));
    }
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public  List<Long> distribute(StockInDTO stockInDTO) {
        List<Long> ids=stockInDTO.getIds();
        List<Long> rights=new ArrayList<>();
        String distribute=stockInDTO.getDistributeBy();
        UserVo userVo=userService.findUserByUsername(distribute);
        if(userVo==null){
            throw new RuntimeException("用户不存在");
        }
        for(Long id :ids){
            TblStock tblStock=new TblStock();
            tblStock.setId(id);
            tblStock.setOrderStatus(OrderStatus.DISTRIBUTED);
            tblStock.setDistributeBy(distribute);
            tblStock.setGmtDistribute(new Date());
            if(this.updateById(tblStock)){
                rights.add(id);
            }
        }
        return rights;
    }

    @Override
    public List<Long> gathering(StockInDTO stockInDTO) {
        List<Long> ids=stockInDTO.getIds();
        List<Long> rights=new ArrayList<>();
        for(Long id :ids){
            TblStock tblStock=new TblStock();
            tblStock.setId(id);
            tblStock.setOrderStatus(OrderStatus.GATHERING_SUCCESS);
            if(this.updateById(tblStock)){
                rights.add(id);
            }
        }
        return rights;
    }



    public Date main(Integer days) {
        Calendar cal = Calendar.getInstance();
        cal.set(1900, 0, 1);
        cal.add(Calendar.DAY_OF_MONTH, days);
        Date date=cal.getTime();
        System.out.print(cal.get(Calendar.YEAR) + "年");
        System.out.print(cal.get(Calendar.MONTH) + 1 + "月");
        System.out.println(cal.get(Calendar.DAY_OF_MONTH) + "日");
        return date;
    }
    private String getXCellVal(HSSFCell cell) {
        switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    //日期型
                    val = fmt.format(cell.getDateCellValue());
                } else {
                    //数字型
                    val = df.format(cell.getNumericCellValue());
                }
                break;
            //文本类型
            case HSSFCell.CELL_TYPE_STRING:
                val = cell.getStringCellValue();
                break;
            //布尔型
            case HSSFCell.CELL_TYPE_BOOLEAN:
                val = String.valueOf(cell.getBooleanCellValue());
                break;
            //空白
            case HSSFCell.CELL_TYPE_BLANK:
                val = cell.getStringCellValue();
                break;
            //错误
            case HSSFCell.CELL_TYPE_ERROR:
                val = "错误";
                break;
            //公式
            case HSSFCell.CELL_TYPE_FORMULA:
                try {
                    val = String.valueOf(cell.getStringCellValue());
                } catch (IllegalStateException e) {
                    val = String.valueOf(cell.getNumericCellValue());
                }
                break;
            default:
                val = cell.getRichStringCellValue() == null ? null : cell.getRichStringCellValue().toString();
        }
        return val;
    }
}
